package com;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SocketHandlerThread implements Runnable {
	private Socket socket;

	public SocketHandlerThread(Socket client) {
		socket = client;
		new Thread(this).start();
	}

	public void run() {
		try {
			DataInputStream input = new DataInputStream(socket.getInputStream());
			byte[] bytelength = new byte[4];

			input.read(bytelength, 0, 4);
			int reslength = Common.byteArrayToInt(bytelength, 0);
			byte[] bytedata = new byte[reslength];
			int jsq = 0;
			while (jsq < reslength) {
				jsq += input.read(bytedata, jsq, reslength - jsq);
			}

			String data = new String(bytedata);
			data = Aes.Decrypt(data, Main.txmy);

			MsgObj obj = MsgObj.fromJson(data);
			OutputStream out = socket.getOutputStream();
			String resmsg = "";
			if (!obj.getType().equals("3") && !obj.getType().equals("4")) {
				MsgHandler.sendMsg(obj);
				resmsg = "1";
			} else if (obj.getType().equals("4")) {
				resmsg = "1";
			} else {
				String url=Main.getUrl();
				resmsg = url == null ? "0" : url;
			}

			reslength = 0;
			if (!resmsg.equals("")) {
				bytedata=resmsg.getBytes();
				bytelength=Common.intToByteArray(bytedata.length);
			}else{
				bytelength=Common.intToByteArray(reslength);
			}
			
			out.write(bytelength);
			if(!resmsg.equals("")) {
				out.write(bytedata);
			}
			
			out.flush();
			out.close();
			input.close();
		} catch (Exception e) {
		} finally {
			if (socket != null) {
				try {
					socket.close();
				} catch (Exception e) {
					socket = null;
				}
			}
		}
	}
}
